<template>
  <div class="consumer-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>用户管理</h2>
    </div>

    <!-- 操作栏 -->
    <div class="operation-bar">
      <!-- 搜索框 -->
      <div class="search-box">
        <el-input
          v-model="searchForm.keyword"
          placeholder="请输入用户名称"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button :icon="Search" @click="handleSearch" />
          </template>
        </el-input>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button type="danger" :icon="Delete" @click="handleBatchDelete" :disabled="selectedConsumers.length === 0">
          批量删除
        </el-button>
      </div>
    </div>

    <!-- 用户表格 -->
    <el-table
      :data="consumerList"
      style="width: 100%"
      v-loading="loading"
      element-loading-text="加载中..."
      @selection-change="handleSelectionChange"
      border
    >
      <!-- 选择列 -->
      <el-table-column type="selection" width="55" />

      <!-- 用户ID -->
      <el-table-column prop="consumerId" label="ID" width="80" />

      <!-- 用户头像 -->
      <el-table-column label="头像" width="120">
        <template #default="scope">
          <div class="consumer-avatar">
            <el-image
                :src="getConsumerImageUrl(scope.row.consumerAvatar)"
                class="avatar-img"
                fit="cover"
                :preview-src-list="[getConsumerImageUrl(scope.row.consumerAvatar)]"
                preview-teleported
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
          </div>
        </template>
      </el-table-column>

      <!-- 用户姓名 -->
      <el-table-column prop="consumerName" label="姓名" min-width="120" />

      <!-- 性别 -->
      <el-table-column label="性别" width="80">
        <template #default="scope">
          <el-tag :type="scope.row.consumerSex === 1 ? 'primary' : 'success'">
            {{ scope.row.consumerSex === 1 ? '男' : '女' }}
          </el-tag>
        </template>
      </el-table-column>

      <!-- 生日 -->
      <el-table-column prop="consumerBirthday" label="生日" width="120">
        <template #default="scope">
          {{ formatDate(scope.row.consumerBirthday) }}
        </template>
      </el-table-column>

      <!-- 地区 -->
      <el-table-column prop="consumerLocation" label="地区" width="120" />

      <!-- 邮箱 -->
      <el-table-column prop="consumerEmail" label="邮箱" min-width="150" />

      <!-- 简介 -->
      <el-table-column prop="consumerSignature" label="简介" min-width="200" show-overflow-tooltip />

      <!-- 操作列 -->
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="scope">
          <el-button
            type="primary"
            link
            :icon="Edit"
            @click="handleEditConsumer(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            type="danger"
            link
            :icon="Delete"
            @click="handleDeleteConsumer(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[5, 10, 20, 50]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 编辑用户对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form
        :model="consumerForm"
        :rules="consumerRules"
        ref="consumerFormRef"
        label-width="80px"
      >
        <el-form-item label="姓名" prop="consumerName">
          <el-input v-model="consumerForm.consumerName" placeholder="请输入用户姓名" />
        </el-form-item>

        <el-form-item label="性别" prop="consumerSex">
          <el-radio-group v-model="consumerForm.consumerSex">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="生日" prop="consumerBirthday">
          <el-date-picker
            v-model="consumerForm.consumerBirthday"
            type="date"
            placeholder="请选择生日"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="地区" prop="consumerLocation">
          <el-input v-model="consumerForm.consumerLocation" placeholder="请输入地区" />
        </el-form-item>

        <el-form-item label="邮箱" prop="consumerEmail">
          <el-input v-model="consumerForm.consumerEmail" placeholder="请输入邮箱" />
        </el-form-item>

        <el-form-item label="简介" prop="consumerSignature">
          <el-input
            v-model="consumerForm.consumerSignature"
            type="textarea"
            :rows="3"
            placeholder="请输入简介"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitConsumerForm" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {Search, Plus, Delete, Edit, Picture} from '@element-plus/icons-vue'
import api from '@/services/api'
import consumerDefaultAvatar from '@/assets/img//singer-default.png'

export default {
  name: 'ConsumerPage',
  components: {
    Search,
    Plus,
    Delete,
    Edit,
    Picture
  },
  setup() {
    // 加载状态
    const loading = ref(false)
    const submitLoading = ref(false)

    // 搜索表单
    const searchForm = reactive({
      keyword: ''
    })

    // 用户列表
    const consumerList = ref([])

    // 选中的用户
    const selectedConsumers = ref([])

    // 分页信息
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })

    // 对话框相关
    const dialogVisible = ref(false)
    const dialogTitle = ref('')
    const isEdit = ref(false)

    // 用户表单
    const consumerForm = reactive({
      consumerId: null,
      consumerName: '',
      consumerSex: 1,
      consumerAvatar: '',
      consumerBirthday: '',
      consumerLocation: '',
      consumerEmail: '',
      consumerSignature: ''
    })

    // 表单验证规则
    const consumerRules = {
      consumerName: [
        { required: true, message: '请输入用户姓名', trigger: 'blur' }
      ],
      consumerEmail: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
      ]
    }

    // 表单引用
    const consumerFormRef = ref(null)

    // 默认头像
    const defaultAvatar = consumerDefaultAvatar

    /**
     * 格式化日期
     * @param {string} date - 日期字符串
     * @returns {string} 格式化后的日期
     */
    const formatDate = (date) => {
      if (!date) return ''
      return date.split(' ')[0]
    }

    /**
     * 获取用户列表
     */
    const fetchConsumerList = async () => {
      loading.value = true
      try {
        let response
        if (searchForm.keyword) {
          // 模糊搜索
          response = await api.consumer.search(searchForm.keyword)
        } else {
          // 获取所有用户
          response = await api.consumer.allConsumer()
        }

        if (response.code === '1') {
          consumerList.value = response.data
          pagination.total = consumerList.value.length
        } else {
          ElMessage.error(response.msg || '获取用户列表失败')
          consumerList.value = []
          pagination.total = 0
        }
      } catch (error) {
        ElMessage.error('获取用户列表失败')
        console.error('Fetch consumer list error:', error)
      } finally {
        loading.value = false
      }
    }

    /**
     * 处理搜索
     */
    const handleSearch = () => {
      pagination.currentPage = 1
      fetchConsumerList()
    }

    /**
     * 处理选择变化
     * @param {Array} selection - 选中的行
     */
    const handleSelectionChange = (selection) => {
      selectedConsumers.value = selection
    }

    /**
     * 处理分页大小变化
     * @param {number} val - 每页条数
     */
    const handleSizeChange = (val) => {
      pagination.pageSize = val
      pagination.currentPage = 1
      fetchConsumerList()
    }

    /**
     * 处理当前页变化
     * @param {number} val - 当前页码
     */
    const handleCurrentChange = (val) => {
      pagination.currentPage = val
      fetchConsumerList()
    }

    /**
     * 处理编辑用户
     * @param {Object} row - 用户数据
     */
    const handleEditConsumer = (row) => {
      dialogTitle.value = '编辑用户'
      isEdit.value = true
      // 确保正确填充所有表单数据
      Object.assign(consumerForm, {
        consumerId: row.consumerId,
        consumerName: row.consumerName,
        consumerSex: row.consumerSex,
        consumerBirthday: row.consumerBirthday ? row.consumerBirthday.split(' ')[0] : '',
        consumerLocation: row.consumerLocation,
        consumerEmail: row.consumerEmail,
        consumerSignature: row.consumerSignature
      })
      dialogVisible.value = true
    }

    /**
     * 处理删除用户
     * @param {Object} row - 用户数据
     */
    const handleDeleteConsumer = async (row) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除用户 "${row.consumerName}" 吗？`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        const response = await api.consumer.delete(row.consumerId)
        if (response.code === '1') {
          ElMessage.success('删除成功')
          await fetchConsumerList()
        } else {
          ElMessage.error(response.msg || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }

    /**
     * 处理批量删除
     */
    const handleBatchDelete = async () => {
      if (selectedConsumers.value.length === 0) {
        ElMessage.warning('请先选择要删除的用户')
        return
      }

      try {
        await ElMessageBox.confirm(
          `确定要删除选中的 ${selectedConsumers.value.length} 个用户吗？`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        // 批量删除
        const deletePromises = selectedConsumers.value.map(consumer =>
          api.consumer.delete(consumer.consumerId)
        )

        const results = await Promise.all(deletePromises)
        const successCount = results.filter(result => result.code === '1').length

        if (successCount > 0) {
          ElMessage.success(`成功删除 ${successCount} 个用户`)
          await fetchConsumerList()
        } else {
          ElMessage.error('删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }

    /**
     * 获取用户图片完整URL
     * @param {string} imagePath - 图片相对路径
     * @returns {string} 完整图片URL
     */
    const getConsumerImageUrl = (imagePath) => {
      // 如果没有图片路径，返回默认图片
      if (!imagePath) return defaultAvatar

      // 如果已经是完整URL则直接返回
      if (imagePath.startsWith('http')) {
        return imagePath
      }

      // 如果是绝对路径（以 / 开头），直接返回
      if (imagePath.startsWith('/')) {
        // 确保路径正确映射到静态资源
        return imagePath
      }

      // 如果是相对路径（如 img/consumerPic/xxx.jpg）
      if (imagePath.startsWith('img/')) {
        return `/${imagePath}`
      }

      // 其他情况使用默认图片
      return defaultAvatar
    }

    /**
     * 提交用户表单
     */
    const submitConsumerForm = async () => {
      if (!consumerFormRef.value) return

      await consumerFormRef.value.validate(async (valid) => {
        if (valid) {
          submitLoading.value = true
          try {
            // 编辑用户时需要检查 consumerId
            if (!consumerForm.consumerId) {
              ElMessage.error('用户ID不能为空！')
              submitLoading.value = false
              return
            }

            // 编辑用户
            const consumerData = {
              consumerId: consumerForm.consumerId,
              consumerName: consumerForm.consumerName,
              consumerSex: consumerForm.consumerSex,
              consumerBirthday: consumerForm.consumerBirthday,
              consumerLocation: consumerForm.consumerLocation,
              consumerEmail: consumerForm.consumerEmail,
              consumerSignature: consumerForm.consumerSignature
            };

            const response = await api.consumer.update(consumerData)

            if (response.code === '1') {
              ElMessage.success('编辑成功')
              dialogVisible.value = false
              await fetchConsumerList()
            } else {
              ElMessage.error(response.msg || '编辑失败')
            }
          } catch (error) {
            ElMessage.error('编辑失败')
            console.error('Submit consumer form error:', error)
          } finally {
            submitLoading.value = false
          }
        }
      })
    }

    /**
     * 处理对话框关闭
     */
    const handleDialogClose = () => {
      if (consumerFormRef.value) {
        consumerFormRef.value.resetFields()
      }
    }

    // 组件挂载时获取数据
    onMounted(() => {
      fetchConsumerList()
    })

    return {
      loading,
      submitLoading,
      searchForm,
      consumerList,
      selectedConsumers,
      pagination,
      dialogVisible,
      dialogTitle,
      isEdit,
      consumerForm,
      consumerRules,
      consumerFormRef,
      defaultAvatar,
      formatDate,
      handleSearch,
      handleSelectionChange,
      handleSizeChange,
      handleCurrentChange,
      handleEditConsumer,
      handleDeleteConsumer,
      handleBatchDelete,
      submitConsumerForm,
      handleDialogClose,
      getConsumerImageUrl
    }
  }
}
</script>

<style scoped>
.consumer-container {
  padding: 20px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.search-box {
  width: 300px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.consumer-avatar {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.avatar-img {
  width: 80px;
  height: 80px;
  border-radius: 50%;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>
